<template>
  <div id="wantJdj">
    <index v-if="!loginResult&&!invite"/>
    <invite v-if="loginResult&&!invite"/>
    <accept v-if="invite&&!register"/>
    <result v-if="register"/>
  </div>
</template>

<script>
import axios from "axios";
axios.defaults.withCredentials = true;
import index from "./index/index.vue";
import invite from "./invite/index.vue";
import accept from "./accept/index.vue";
import result from "./accept/result.vue";
import store from "../../store.js";
export default {
  name: "wantJdj",
  components: {
    index,
    invite,
    accept,
    result
  },
  computed: {
    serveAPI: {
      get() {
        let serve = {};
        let portAddress = store.state.apiPort.map(
          e => store.state.apiOrigin + e.split(":")[1]
        );
        let portName = store.state.apiPort.map(e => e.split(":")[0]);
        for (let i = 0; i < portName.length; i++) {
          serve[portName[i]] = portAddress[i];
        }
        return serve;
      },
      set() {}
    },
    loginResult: {
      get() {
        return store.state.loginResult;
      },
      set() {}
    },
    invite: {
      get() {
        return store.state.invite;
      },
      set() {}
    },
    register: {
      get() {
        return store.state.register;
      },
      set() {}
    },
    appId: {
      get() {
        return store.state.appId;
      }
    },
    appSecret: {
      get() {
        return store.state.appSecret;
      }
    },
    wxApp: {
      get() {
        return store.state.wxApp;
      },
      set() {}
    },
    wxEnv: {
      get() {
        return store.state.wxEnv;
      },
      set() {}
    },
    cookieInviteId: {
      get() {
        return store.state.cookieInviteId;
      }
    }
  },
  methods: {
    //----------------------------------------------------
    // default
    init() {
      this.systemTest();
      this.getLifeTime();
      this.verityWxEnv();
      this.setAlert();
      this.verityCenter();
    },
    setAlert() {
      window.alert = function(name) {
        let iframe = document.createElement("IFRAME");
        iframe.style.display = "none";
        iframe.setAttribute("src", "data:text/plain,");
        document.documentElement.appendChild(iframe);
        window.frames[0].window.alert(name);
        iframe.parentNode.removeChild(iframe);
      };
    },
    //----------------------------------------------------
    // cookie
    cookieGet(key) {
      key = key + "=";
      let cookieList = document.cookie.split(";");
      for (let i = 0; i < cookieList.length; i++) {
        const item = cookieList[i].trim();
        if (item.indexOf(key) == 0)
          return item.substring(key.length, item.length);
      }
      return;
    },
    cookieSet(key, value, day) {
      let d = new Date();
      d.setTime(d.getTime() + day * 24 * 60 * 60 * 1000);
      let expires = "expires=" + d.toGMTString();
      document.cookie = key + "=" + value + ";" + expires;
    },
    //----------------------------------------------------
    // verity
    getCalfKey() {
      let href = location.href.split("?");
      if (href.length > 1) href = href[1].split("&");
      else return;
      for (let i = 0; i < href.length; i++) {
        if (href[i].match("calfKey")) return href[i].split("=")[1];
      }
    },
    verityWx2() {
      let href = window.location.href;
      if (href.match("code=")) {
        let code = href.split("code=")[1].split("&")[0];
        // alert("获取到的code：" + code);
        // console.log("获取到的code：" + code)
        axios.get(this.serveAPI.wxLogin + code).then(res => {
          if (res.data.error) {
            alert(res.data.error);
          } else {
            // alert('授权信息' + JSON.stringify(res.data.object))
            if (!res.data.object.wxnickName) {
              // alert('新用户，进行显式授权')
              window.location.href =
                "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
                this.wxApp.appId +
                "&redirect_uri=" +
                encodeURIComponent(href.split("?")[0]) +
                "&response_type=code&scope=" +
                this.wxApp.scopeInfo +
                "#wechat_redirect&connect_redirect=1";
            } else {
              // alert('授权信息' + JSON.stringify(res.data.object))
              if (res.data.object.calfKey) {
                // alert('已绑定的key：' + res.data.object.calfKey)
                store.commit("upload", {
                  prope: "calfKey",
                  data: res.data.object.calfKey
                });
                this.getInviteList();
              }
            }
          }
        });
      } else {
        // alert('进行静默授权，当前URL：' + href)
        window.location.href =
          "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
          this.wxApp.appId +
          "&redirect_uri=" +
          encodeURIComponent(href) +
          "&response_type=code&scope=" +
          this.wxApp.scopeBase +
          "#wechat_redirect&connect_redirect=1";
      }
    },
    verityWx3() {
      let href = window.location.href;
      //alert("当前URL：" + href);
      let codeCookie = this.cookieGet("CODE");
      let code = null;
      if (href.match("code=")) code = href.split("code=")[1].split("&")[0];
      // alert("当前code：" + code + '/' + codeCookie);

      if (code || codeCookie) {
        if (code) {
          // alert("设置本地code：" + code);
          this.cookieSet("CODE", code);
          // alert("清除URL code");
          window.location.href = window.location.href.split("?")[0];
        }
        if (codeCookie) {
          // alert("获取到的本地code：" + codeCookie);
          axios.get(this.serveAPI.wxLogin + codeCookie).then(res => {
            this.cookieSet("CODE", "");
            // alert("清除本地code：" + this.cookieGet('CODE', ''));
            if (res.data.error) {
              alert(res.data.error);
            } else {
              // alert('授权信息' + JSON.stringify(res.data.object))
              if (!res.data.object.wxnickName) {
                // alert('新用户，进行显式授权')
                window.location.href =
                  "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
                  this.wxApp.appId +
                  "&redirect_uri=" +
                  encodeURIComponent(href.split("?")[0]) +
                  "&response_type=code&scope=" +
                  this.wxApp.scopeInfo +
                  "#wechat_redirect&connect_redirect=1";
              } else {
                // alert('授权信息' + JSON.stringify(res.data.object))
                if (res.data.object.calfKey) {
                  // alert('已绑定的key：' + res.data.object.calfKey)
                  store.commit("upload", {
                    prope: "calfKey",
                    data: res.data.object.calfKey
                  });
                  this.getInviteList();
                }
              }
            }
          });
        }
        // console.log("获取到的code：" + code)
      } else {
        // alert('进行静默授权，当前URL：' + href)
        window.location.href =
          "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
          this.wxApp.appId +
          "&redirect_uri=" +
          encodeURIComponent(href) +
          "&response_type=code&scope=" +
          this.wxApp.scopeBase +
          "#wechat_redirect&connect_redirect=1";
      }
    },
    verityWx4() {
      // alert('开始授权流程')
      let PageURL = window.location.href;
      let baseURL = this.verityWxURL(this.wxApp.scopeBase);
      let infoURL = this.verityWxURL(this.wxApp.scopeInfo);
      let codeUrl = this.getUrlVar("code");
      let codeSession = sessionStorage.getItem("code");
      // alert('PageURL:' + PageURL + '-------' + 'codeUrl:' + codeUrl + '------' + 'codeSession:' + codeSession)
      if (!codeUrl && !codeSession) {
        // alert('获取code')
        window.location.replace(baseURL);
      } else if (!codeSession) {
        // alert('设置session')
        sessionStorage.setItem("code", codeUrl);
        window.location.replace(PageURL.split("?")[0]);
      } else {
        // alert('拿到sessionCode：' + codeSession + '---进行授权')
        sessionStorage.setItem("code", "");
        axios.get(this.serveAPI.wxLogin + codeSession).then(res => {
          // alert('接口返回信息' + JSON.stringify(res))

          if (res.data.error) {
            alert(res.data.error);
          } else {
            // alert('授权信息' + JSON.stringify(res.data.object))
            if (!res.data.object.wxnickName) {
              // alert('新用户，进行显式授权')
              window.location.replace(infoURL);
            } else {
              // alert('授权信息' + JSON.stringify(res.data.object))
              if (res.data.object.calfKey) {
                // alert('已绑定的key：' + res.data.object.calfKey)
                store.commit("upload", {
                  prope: "calfKey",
                  data: res.data.object.calfKey
                });
                this.getInviteList();
              }
            }
          }
        });
      }
    },
    verityWx() {
      // alert('开始授权流程')
      let PageURL = window.location.href;
      // let baseURL = this.verityWxURL(this.wxApp.scopeBase);
      let infoURL = this.verityWxURL(this.wxApp.scopeInfo);
      let codeUrl = this.getUrlVar("code");
      let codeSession = sessionStorage.getItem("code");
      // alert('PageURL:' + PageURL + '-------' + 'codeUrl:' + codeUrl + '------' + 'codeSession:' + codeSession)
      if (!codeUrl && !codeSession) {
        // alert('获取code')
        window.location.replace(infoURL);
      } else if (!codeSession) {
        // alert('设置session')
        sessionStorage.setItem("code", codeUrl);
        window.location.replace(PageURL.split("?")[0]);
        // window.history.pushState(null, null, PageURL.split("?")[0])
      } else {
        // alert('拿到sessionCode：' + codeSession + '---进行授权')
        sessionStorage.setItem("code", "");
        axios.get(this.serveAPI.wxLogin + codeSession).then(res => {
          // alert('接口返回信息' + JSON.stringify(res))
          if (res.data.error) {
            alert(res.data.error);
          } else {
            // alert('授权信息' + JSON.stringify(res.data.object))
            if (res.data.object.calfKey) {
              // alert('已绑定的key：' + res.data.object.calfKey)
              store.commit("upload", {
                prope: "calfKey",
                data: res.data.object.calfKey
              });
              this.getInviteList();
            }
          }
        });
      }
    },
    getUrlVar(e) {
      let href = location.href.split("?");
      if (href.length > 1) {
        for (let i = 0; i < href.length; i++) {
          const element = href[i];
          if (element.match(e)) return element.split("=")[1].split("&")[0];
        }
      } else {
        return null;
      }
    },
    verityWxURL(e) {
      let href = location.href;
      return (
        "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
        this.wxApp.appId +
        "&redirect_uri=" +
        encodeURIComponent(href.split("?")[0]) +
        "&response_type=code&scope=" +
        e +
        "&state=123&connect_redirect=1#wechat_redirect"
      );
    },
    verityWxEnv() {
      let ua = window.navigator.userAgent;
      if (/MicroMessenger/.test(ua))
        store.commit("upload", { prope: "wxEnv", data: true });
    },
    verityCenter() {
      // 判断邀请关系
      if (this.getCalfKey()) {
        // alert('是被邀请人，邀请人的calfKey：' + this.getCalfKey())
        store.commit("upload", {
          prope: "invite",
          data: true
        });
        store.commit("upload", {
          prope: "calfKey",
          data: this.getCalfKey()
        });
        this.getInviter(this.getCalfKey());
      } else {
        // 微信验证相关
        if (this.wxEnv) {
          // 微信环境判断
          this.verityWx();
        }
      }
    },
    //----------------------------------------------------
    // serve
    getInviteList() {
      axios.get(this.serveAPI.inviteList).then(res => {
        // alert('获取邀请列表：' + JSON.stringify(res.data));
        if (res.data.object.length > 0) {
          let list = [];
          res.data.object.map(e => {
            list.push(e.headImageUrl || null);
          });
          store.commit("upload", { prope: "inviteList", data: list });
          // alert('保存的邀请列表：' + store.state.inviteList)
        }
      });
    },
    getInviter(key) {
      axios.get(this.serveAPI.inviter + key).then(res => {
        // alert('获取邀请人信息' + JSON.stringify(res));
        if (res.data.object.count >= 10) {
          alert("邀请名额已满哦");
        }
        store.commit("upload", { prope: "inviter", data: res.data.object });
      });
    },
    getLifeTime() {
      axios.get(this.serveAPI.getLifeTime).then(res => {
        let info = "";
        let begin = this.getTs(res.data.object.beginTime);
        let end = this.getTs(res.data.object.endTime);
        let current = new Date().getTime();
        // alert(begin + '|' + end + '|' + current)
        if (current < begin) info = "活动未开始";
        if (current > end) info = "活动已经结束";
        store.commit("upload", { prope: "lifeInfo", data: info });
      });
    },
    getTs(time) {
      var arr = time.split(/[- :]/),
        _date = new Date(arr[0], arr[1] - 1, arr[2], arr[3], arr[4], arr[5]),
        timeStr = Date.parse(_date);
      return timeStr;
    },
    //----------------------------------------------------
    // test
    systemTest() {
      let ua = window.navigator.userAgent;
      if (/\(i[^;]+;( U;)? CPU.+Mac OS X/.test(ua)) {
        // console.log('苹果')
      } else {
        // console.log("安卓");
        store.commit("upload", { prope: "system", data: "android" });

        // alert('禁用返回键')

        let XBack = {};

        (function(XBack) {
          XBack.STATE = "x - back";
          XBack.element;

          XBack.onPopState = function(event) {
            event.state === XBack.STATE && XBack.fire();
            XBack.record(XBack.STATE); //初始化事件时，push一下
          };

          XBack.record = function(state) {
            history.pushState(state, null, location.href);
          };

          XBack.fire = function() {
            var event = document.createEvent("Events");
            event.initEvent(XBack.STATE, false, false);
            XBack.element.dispatchEvent(event);
          };

          XBack.listen = function(listener) {
            XBack.element.addEventListener(XBack.STATE, listener, false);
          };

          XBack.init = function() {
            XBack.element = document.createElement("span");
            window.addEventListener("popstate", XBack.onPopState);
            XBack.record(XBack.STATE);
          };
        })(XBack);

        XBack.init();
        XBack.listen(function() {});
      }
    }
  },
  created() {
    this.init();
  },
  mounted() {
    window.addEventListener("popstate", () => {
      // alert('你别跑')
    });
  }
};
</script>
<style lang="stylus">
#wantJdj {
  width 100vw
  max-width 420px
  min-width 320px
  min-height 550px
  max-height 820px
  position relative
  // box-shadow 0 1px 3px rgba(26, 26, 26, 0.1)
  // @media only screen and (min-width: 420px) {
  // position absolute
  // left 50%
  // top 50%
  // transform translateX(-50%) translateY(-50%)
  // border-radius 3px
  // overflow hidden
  // }
}
</style>
